package com.corn.juc.demo;

import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2020/12/31 17:06
 */
//一个初始值为0的变量，两个线程对其交替操作，一个加1，一个减1，来5轮
class ShareData {
    private volatile boolean Flag = true;

    private final BlockingQueue<Integer> blockingQueue;

    private AtomicInteger number = new AtomicInteger();

    ShareData(BlockingQueue<Integer> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    public void produce() {
        int data;
        while (Flag) {
            data = this.number.incrementAndGet();
            try {
                if (blockingQueue.offer(data, 1, TimeUnit.SECONDS)) {
                    System.out.println(Thread.currentThread().getName() + "\t 插入数据" + data);
                } else {
                    System.out.println("队列已满无法插入...");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void consumer() {
        Integer data;
        try {
            while (Flag) {
                data = blockingQueue.poll(1, TimeUnit.SECONDS);
                if (Objects.nonNull(data)) {
                    System.out.println("从队列中消费 " + data);
                } else {
                    System.out.println("队列为空无法取出");
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        this.Flag = false;
    }
}

public class ProducerAndConsumerCase {

    public static void main(String[] args) throws InterruptedException {
        ShareData shareData = new ShareData(new ArrayBlockingQueue<Integer>(3));
        new Thread("producer") {
            @Override
            public void run() {
                shareData.produce();
            }
        }.start();

        new Thread("consumer") {
            @Override
            public void run() {
                shareData.consumer();
            }
        }.start();
        // 5s 之后停止
        TimeUnit.SECONDS.sleep(7);
        System.out.println("7s 之后停止");
        shareData.stop();

    }

}
